package com.xayy.health.mgt.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.mybatis.base.BaseServiceImpl;
import com.xayy.health.core.constant.TableNameConstant;
import com.xayy.health.core.enums.RunningStatusEnum;
import com.xayy.health.core.enums.SystemModelTypeEnum;
import com.xayy.health.core.enums.TaskInfoStatusEnum;
import com.xayy.health.mgt.mapper.*;
import com.xayy.health.mgt.model.HealthAlgorithmManage;
import com.xayy.health.mgt.model.TaskChildInfo;
import com.xayy.health.mgt.model.TaskInfo;
import com.xayy.health.mgt.model.vo.TaskVo;
import com.xayy.health.mgt.service.HealthAlgorithmManageService;
import com.xayy.health.mgt.service.TaskChildInfoService;
import com.xayy.health.mgt.service.TaskInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务子列表
 *
 * @author zhangxa
 */
@Service
public class TaskChildInfoServiceImpl extends BaseServiceImpl<TaskChildInfo> implements TaskChildInfoService {

    @Autowired
    private TaskChildInfoMapper taskChildInfoMapper;

    @Autowired
    private TaskInfoService taskInfoService;
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private TaskChildInfoService taskChildInfoService;
    @Autowired
    private TaskParamInfoMapper taskParamInfoMapper;
    @Autowired
    private HealthAlgorithmManageService healthAlgorithmManageService;
    @Autowired
    private TyDataMapper tyDataMapper;
    @Autowired
    private PhDataMapper phDataMapper;
    @Autowired
    private TcDataMapper tcDataMapper;
    @Autowired
    private CalculateDataMapper calculateDataMapper;
    @Autowired
    private DiagnoseMultipleParametersDataMapper diagnoseMultipleParametersDataMapper;
    @Autowired
    private DiagnosePredictDataMapper diagnosePredictDataMapper;
    @Autowired
    private SelectTelemetryDataSourceMapper selectTelemetryDataSourceMapper;

    /**
     * 批量（单个）删除任务及其子任务
     *
     * @param taskVo 任务入参
     * @return ResultBody
     */
    @Override
    public CheckResult<Object> deleteChildTask(TaskVo taskVo) {
        // 批量删任务
        if (CollUtil.isNotEmpty(taskVo.getTaskId())) {
            // 防止脏数据
            taskInfoMapper.updateBatchStatus(taskVo.getTaskId());
            List<Long> taskId = taskVo.getTaskId();
            List<TaskInfo> taskInfos = taskInfoService.selectByIds(taskVo.getTaskId());
            //预测数据
            if (taskVo.getType() == 3) {
                List<Long> predictIdList = taskInfos.stream().filter(item -> item.getType().equals(SystemModelTypeEnum.TREND_FORECASTING.getSystemModelTypeCode())).map(TaskInfo::getId).collect(Collectors.toList());
                taskInfoMapper.deleteCalculateData(predictIdList);
            }
            ArrayList<Long> idLongs = new ArrayList<>();
            for (Long aLong : taskId) {
                List<TaskChildInfo> taskChildInfos = select(TaskChildInfo.builder().taskId(aLong).build());
                for (TaskChildInfo taskChildInfo : taskChildInfos) {
                    idLongs.add(taskChildInfo.getId());
                }
            }
            if (CollUtil.isNotEmpty(idLongs)) {
                tyDataMapper.deleteTbTyData(idLongs);
                tcDataMapper.deleteTbTcData(idLongs);
                phDataMapper.deleteTbPhData(idLongs);
                if (taskVo.getType() == 2) {
                    diagnoseMultipleParametersDataMapper.deleteDiagnoseMultipleParametersData(idLongs);
                }
                taskChildInfoService.deleteByIds(idLongs);
            }
            taskParamInfoMapper.deleteBatchParams(taskVo.getTaskId());
            taskInfoService.deleteByIds(taskVo.getTaskId());
        }

        if (CollUtil.isNotEmpty(taskVo.getTaskChildId())) {
            // 批量删子任务
            List<Long> taskChildId = taskVo.getTaskChildId();
            taskChildInfoMapper.updateByIds(taskChildId);
            tyDataMapper.deleteTbTyData(taskChildId);
            tcDataMapper.deleteTbTcData(taskChildId);
            phDataMapper.deleteTbPhData(taskChildId);
            diagnoseMultipleParametersDataMapper.deleteDiagnoseMultipleParametersData(taskVo.getTaskChildId());
            /*删除运行时保存的使用后的遥测数据*/
            taskChildId.forEach(item -> selectTelemetryDataSourceMapper.deleteTable(TableNameConstant.RUN_TASK_TELEMETRY + item));
        }
        return CheckResult.success("删除成功");
    }

    /**
     * 子任务参数处理展示
     *
     * @param taskInfo 任务信息入参
     * @return ResultBody
     */
    @Override
    public CheckResult<List<HealthAlgorithmManage>> getAlgorithmTypeByChild(TaskInfo taskInfo) {
        TaskInfo info = taskInfoService.selectById(taskInfo.getId());
        if (BeanUtil.isNotEmpty(info)) {
            List<HealthAlgorithmManage> list = CollUtil.newArrayList();
            List<HealthAlgorithmManage> healthAlgorithmManages = healthAlgorithmManageService.selectAll();
            for (HealthAlgorithmManage algorithmManage : healthAlgorithmManages) {
                if (algorithmManage.getAlgorithmCode().equals(info.getTyTag())) {
                    list.add(algorithmManage);
                } else if (algorithmManage.getAlgorithmCode().equals(info.getTcTag())) {
                    list.add(algorithmManage);
                } else if (algorithmManage.getAlgorithmCode().equals(info.getPhTag())) {
                    list.add(algorithmManage);
                }
            }
            return CheckResult.success(list);
        }
        return CheckResult.fail("没有查询到该任务");
    }


    /**
     * 获取子任务信息根据开始时间
     *
     * @param taskInfo 入参
     * @return List<TaskChildInfo>
     */
    @Override
    public List<TaskChildInfo> selectTaskChildListByTime(TaskInfo taskInfo) {
        return taskChildInfoMapper.selectTaskChildListByTime(taskInfo);
    }

    @Override
    public CheckResult<Object> updateStatusData(TaskInfo taskInfo) {
        List<Long> taskChildIds = null;
        //区分单参数和模型
        Integer isCaseOne = null;
        //区分是否是多参数
        Integer checkMultiparameter = null;
        //1长期运行2阶段性运行
        Integer runningStatus = null;
        //重启
        if (taskInfo.getStatus().equals(TaskInfoStatusEnum.RUNNING.getStatusCode())) {
            TaskInfo info =null;
            if (ObjectUtil.isNotNull(taskInfo.getId())) {
                info = taskInfoService.selectById(taskInfo.getId());
                List<TaskChildInfo> taskChildInfoList = taskChildInfoService.selectTaskChildListByTime(taskInfo);
                if (CollUtil.isNotEmpty(taskChildInfoList)) {
                    taskChildIds = taskChildInfoList.stream().map(TaskChildInfo::getId).collect(Collectors.toList());
                }
                if (BeanUtil.isNotEmpty(info)) {
                    isCaseOne = info.getIsCaseOne();
                    checkMultiparameter = info.getCheckMultiparameter();
                    runningStatus = info.getRunningStatus();
                }
            }
            if (taskInfo.getType().equals(SystemModelTypeEnum.TREND_FORECASTING.getSystemModelTypeCode())) {
                CheckResult<TaskInfo> taskResult=taskInfoService.selectTaskInfo(taskInfo.getId());
                if(null!=taskResult){
                    TaskInfo taskBaseInfo=taskResult.getData();
                    if(null!=taskBaseInfo){
                        //根据任务开始时间计算出任务结束时间
                        DateTime endTime=DateUtil.offsetMinute(taskInfo.getStartTime(), Integer.parseInt(taskBaseInfo.getCycle()));
                        taskInfo.setEndTime(endTime);
                        taskInfoService.updateByIdSelective(taskInfo);
                        if (1 == taskInfo.getStatus()) {
                            calculateDataMapper.deleteCalculateData(taskInfo);
                        }
                    }
                }
            } else if (taskInfo.getType().equals(SystemModelTypeEnum.POST_HOC_DIAGNOSIS.getSystemModelTypeCode())) {
                if (runningStatus.equals(RunningStatusEnum.LONG_RUNNING.getCode())) {
                    taskInfo.setLongRunningTime(taskInfo.getEndTime());
                }
                taskInfo.setDateEndTime(taskInfo.getEndTime());
                taskInfoService.updateByIdSelective(taskInfo);
                taskChildInfoService.deleteByIds(taskChildIds);
                if (ObjectUtil.isNotNull(isCaseOne) || ObjectUtil.isNotNull(checkMultiparameter)) {
                    //双参数
                    if (checkMultiparameter.equals(1)) {
                        diagnoseMultipleParametersDataMapper.deleteDiagnoseMultipleParametersData(taskChildIds);
                    } else {
                        //单参数
                        if (isCaseOne.equals(0)) {
                            if(null!=taskChildIds){
                                diagnoseMultipleParametersDataMapper.deleteDiagnoseMultipleParametersData(taskChildIds);
                            }
                        } else {
                            //单参数模型
                            calculateDataMapper.deleteCalculateDataByIds(taskChildIds);
                            diagnosePredictDataMapper.deletePredictDataByIds(taskChildIds);
                        }
                    }
                }
            } else if (taskInfo.getType().equals(SystemModelTypeEnum.DATA_PROCESSING.getSystemModelTypeCode())) {
                taskInfoService.updateByIdSelective(taskInfo);
                if (CollUtil.isNotEmpty(taskChildIds)) {
                    taskChildInfoService.deleteByIds(taskChildIds);
                    tyDataMapper.deleteTbTyData(taskChildIds);
                    phDataMapper.deleteTbPhData(taskChildIds);
                    tcDataMapper.deleteTbTcData(taskChildIds);
                }
            }
        } else {
            //停止状态
            if (taskInfo.getType().equals(SystemModelTypeEnum.POST_HOC_DIAGNOSIS.getSystemModelTypeCode())) {
                taskInfo.setEndTime(DateUtil.date());
                taskInfoService.updateByIdSelective(taskInfo);
            } else {
                //0停止1启动
                taskInfoService.updateByIdSelective(taskInfo);
            }
        }
        return CheckResult.success("更新成功");
    }
}
